package io.github.zeleven.mua.slice;

import io.github.zeleven.mua.ResourceTable;
import io.github.zeleven.mua.bean.SliceCallBack;
import io.github.zeleven.mua.bean.StringCache;
import io.github.zeleven.mua.fraction.HelpFraction;
import io.github.zeleven.mua.fraction.MainFraction;
import io.github.zeleven.mua.utl.PreferenceUtil;
import io.github.zeleven.mua.utl.ScreenUtils;
import io.github.zeleven.mua.view.SlidingDrawer;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;

import java.util.Locale;

/**
 * MainAbilitySlice
 *
 * @since 2021-05-11
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final int INT = 0x001234;
    private static HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, INT, "zf------");
    private static final int SIX = 6;
    private static final int SEVEN = 7;
    private static final int INT_99 = 7;
    private static final int INT_3 = 3;
    private static final int INT_50 = 50;
    private boolean isOpen = false;
    private SlidingDrawer drawer1;
    private Image igLeft;
    private Image editadd;
    private Image igSearch;
    private Image igdialog;
    private Text appName;
    private Image showsearch;
    private TextField textField;
    private boolean isBack = false;
    private boolean isHelp = false;
    private StackLayout stackLayout;
    private DirectionalLayout theme;
    private Image close;
    private Image true1;
    private Image true2;
    private Image true3;
    private Image false1;
    private Image false2;
    private Image false3;
    private Text titile1;
    private Text titile2;
    private Text titile3;
    private Text insert;
    private DependentLayout auto;
    private DependentLayout english;
    private DependentLayout chineses;
    private boolean isVisible = true;
    private SliceCallBack sliceCallBack = new SliceCallBack() {
        @Override
        public void ClickType(int type) {
            if (type == INT_3) {
                present(new HelpFraction(), new Intent());
                isHelp = true;
            }
        }
    };
    private MainFraction mainFraction = new MainFraction(this, sliceCallBack);

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage();
        if (language.equals("zh")) {
            setCacheStatic(StringCache.Chinese);
        } else if (language.equals("en")) {
            setCacheStatic(StringCache.English);
        }
        ((FractionAbility) getAbility()).getFractionManager()
                .startFractionScheduler()
                .replace(ResourceTable.Id_fragment_container, mainFraction)
                .submit();
        initView();
        stackLayout = (StackLayout) findComponentById(ResourceTable.Id_fragment_container);
        appName = (Text) findComponentById(ResourceTable.Id_toolbar_tf);
        showsearch = (Image) findComponentById(ResourceTable.Id_show_ig_search);
        textField = (TextField) findComponentById(ResourceTable.Id_show_textfield);
        theme = (DirectionalLayout) findComponentById(ResourceTable.Id_theme_main_fragment);
        theme.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                isOpen = false;
            }
        });

        textField.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if (s.length() > 0) {
                    showsearch.setVisibility(Component.HIDE);
                    close.setVisibility(Component.VISIBLE);
                } else {
                    showsearch.setVisibility(Component.VISIBLE);
                    close.setVisibility(Component.HIDE);
                }
            }
        });

        textField.setKeyEventListener(new Component.KeyEventListener() {
            @Override
            public boolean onKeyEvent(Component component, KeyEvent keyEvent) {
                if (component.hasFocus()) {
                    if (keyEvent.isKeyDown()) {
                        if (keyEvent.getKeyCode() == keyEvent.KEY_ENTER) {
                            mainFraction.setText(textField.getText());
                        }
                    }
                }
                return false;
            }
        });

        close.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                textField.setText("");
            }
        });

        igdialog.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                PopupDialog dialog = new PopupDialog(MainAbilitySlice.this, null);
                Component parse = LayoutScatter.getInstance(MainAbilitySlice.this)
                        .parse(ResourceTable.Layout_sort_layout, null, false);
                dialog.setCustomComponent(parse);
                dialog.setAlignment(LayoutAlignment.RIGHT | LayoutAlignment.TOP);
                dialog.setSize(ScreenUtils.getDisplayWidth(MainAbilitySlice.this) / SEVEN * INT_3,
                        DirectionalLayout.LayoutConfig.MATCH_CONTENT);
                dialog.setAutoClosable(true);
                dialog.show();
                Text text = (Text) parse.findComponentById(ResourceTable.Id_sort_text);
                cutLanguage(text, ResourceTable.String_sort_dailog,
                        ResourceTable.String_en_sort_dailog,
                        ResourceTable.String_tw_sort_dailog);
                text.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        dialog.remove();
                        sortbyDiarLog(getContext());
                    }
                });
            }
        });

        igSearch.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                isBack = true;
                igLeft.setPixelMap(ResourceTable.Media_ic_back);
                showsearch.setVisibility(Component.VISIBLE);
                textField.setVisibility(Component.VISIBLE);
                igSearch.setVisibility(Component.HIDE);
                appName.setVisibility(Component.HIDE);
            }
        });

        editadd.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                present(new EditAbilitySlice(), new Intent());
            }
        });

        igLeft.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isBack) {
                    backEdit();
                } else {
                    drawer1.animateOpen();
                }
            }
        });

        drawer1.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isOpen) {
                    drawer1.animateClose();
                    isOpen = false;
                } else {
                    if (isBack) {
                        backEdit();
                    } else {
                        drawer1.animateOpen();
                        isOpen = true;
                    }
                }
            }
        });
    }

    /**
     * static赋值
     *
     * @param anInt static int type
     */
    public static void setCacheStatic(final int anInt) {
        StringCache.getInstance().setLanguageType(anInt);
    }

    private void cutLanguage(Text text, int chResource, int enResource, int twResource) {
        int anInt = PreferenceUtil.getInstance().getInt("int", 0);
        StringCache.getInstance().setLanguageType(anInt);
        if (StringCache.getInstance().getLanguageType() == StringCache.Default || StringCache.getInstance().getLanguageType() == StringCache.Chinese) {
            text.setText(this.getString(chResource));
        } else if (StringCache.getInstance().getLanguageType() == StringCache.English) {
            text.setText(this.getString(enResource));
        } else if (StringCache.getInstance().getLanguageType() == StringCache.Chinesefont) {
            text.setText(this.getString(twResource));
        }
    }

    private void backEdit() {
        igLeft.setPixelMap(ResourceTable.Media_title_left);
        textField.setVisibility(Component.HIDE);
        igSearch.setVisibility(Component.VISIBLE);
        appName.setVisibility(Component.VISIBLE);
        close.setVisibility(Component.HIDE);
        textField.setText("");
        clearFocus(textField);
        isBack = false;
        showsearch.setVisibility(Component.HIDE);
    }

    private void sortbyDiarLog(Context context) {
        ComponentContainer customToastLayout = (ComponentContainer) LayoutScatter
                .getInstance(context).parse(ResourceTable.Layout_dialog_sort_by, null, false);
        ComponentContainer.LayoutConfig layoutConfig = new ComponentContainer.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        customToastLayout.setLayoutConfig(layoutConfig);
        CommonDialog toastDialog = new CommonDialog(context);
        toastDialog.setContentCustomComponent(customToastLayout);
        toastDialog.setAutoClosable(true);
        toastDialog.setSize(ScreenUtils.getDisplayWidth(context) / SEVEN * SIX,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        toastDialog.setAlignment(LayoutAlignment.CENTER);
        toastDialog.show();
        initDialogView(customToastLayout);
        Text mContent = (Text) customToastLayout.findComponentById(ResourceTable.Id_tv_content);
        mContent.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toastDialog.destroy();
            }
        });
    }

    private void initDialogView(ComponentContainer customToastLayout) {
        auto = (DependentLayout) customToastLayout.findComponentById(ResourceTable.Id_dl_modify);
        english = (DependentLayout) customToastLayout.findComponentById(ResourceTable.Id_dl_create);
        chineses = (DependentLayout) customToastLayout.findComponentById(ResourceTable.Id_dl_title);
        true1 = (Image) customToastLayout.findComponentById(ResourceTable.Id_ig_true1);
        true2 = (Image) customToastLayout.findComponentById(ResourceTable.Id_ig_true2);
        true3 = (Image) customToastLayout.findComponentById(ResourceTable.Id_ig_true3);
        false1 = (Image) customToastLayout.findComponentById(ResourceTable.Id_ig_false1);
        false2 = (Image) customToastLayout.findComponentById(ResourceTable.Id_ig_false1);
        false3 = (Image) customToastLayout.findComponentById(ResourceTable.Id_ig_false1);
        titile1 = (Text) customToastLayout.findComponentById(ResourceTable.Id_tv_title1);
        titile2 = (Text) customToastLayout.findComponentById(ResourceTable.Id_tv_title2);
        titile3 = (Text) customToastLayout.findComponentById(ResourceTable.Id_tv_title3);
        insert = (Text) customToastLayout.findComponentById(ResourceTable.Id_tv_content);
        Text sort = (Text) customToastLayout.findComponentById(ResourceTable.Id_tx_sort_dailog);
        true1.setClickedListener(this);
        true2.setClickedListener(this);
        true3.setClickedListener(this);
        false1.setClickedListener(this);
        false2.setClickedListener(this);
        false3.setClickedListener(this);
        auto.setClickedListener(this);
        english.setClickedListener(this);
        chineses.setClickedListener(this);

        cutLanguage(sort, ResourceTable.String_sort_dailog,
                ResourceTable.String_en_sort_dailog,
                ResourceTable.String_tw_sort_dailog);
        cutLanguage(titile1, ResourceTable.String_choice_item_create_time_sort,
                ResourceTable.String_en_choice_item_create_time_sort,
                ResourceTable.String_tw_choice_item_create_time_sort);
        cutLanguage(titile2, ResourceTable.String_choice_item_modify_time_sort,
                ResourceTable.String_en_choice_item_modify_time_sort,
                ResourceTable.String_tw_choice_item_modify_time_sort);
        cutLanguage(titile3, ResourceTable.String_choice_item_title_sort,
                ResourceTable.String_en_choice_item_title_sort,
                ResourceTable.String_tw_choice_item_title_sort);
        cutLanguage(insert, ResourceTable.String_cancel,
                ResourceTable.String_en_cancel,
                ResourceTable.String_tw_cancel);
    }

    private void initView() {
        drawer1 = (SlidingDrawer) findComponentById(ResourceTable.Id_slide);
        drawer1.setWidth(INT_50);
        igLeft = (Image) findComponentById(ResourceTable.Id_ig_left);
        editadd = (Image) findComponentById(ResourceTable.Id_edit_add);
        igSearch = (Image) findComponentById(ResourceTable.Id_ig_search);
        igdialog = (Image) findComponentById(ResourceTable.Id_ig_dialog);
        close = (Image) findComponentById(ResourceTable.Id_ic_close);
    }

    @Override
    public void onActive() {
        super.onActive();
        if (mainFraction != null) {
            mainFraction.readFile();
            mainFraction.cutLanguage();
            HiLog.info(hiLogLabel, "onActive");
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_dl_modify:
                int a = 1;
                if (a == 1) {
                    true1.setVisibility(Component.VISIBLE);
                    true2.setVisibility(Component.INVISIBLE);
                    true3.setVisibility(Component.INVISIBLE);
                }
                break;
            case ResourceTable.Id_dl_create:
                int b = 1;
                if (b == 1) {
                    true2.setVisibility(Component.VISIBLE);
                    true1.setVisibility(Component.INVISIBLE);
                    true3.setVisibility(Component.INVISIBLE);
                }
                break;
            case ResourceTable.Id_dl_title:
                int c = 1;
                if (c == 1) {
                    true3.setVisibility(Component.VISIBLE);
                    true2.setVisibility(Component.INVISIBLE);
                    true1.setVisibility(Component.INVISIBLE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onBackPressed() {
        if (isHelp) {
            HiLog.info(hiLogLabel, "返回");
            ((FractionAbility) getAbility()).getFractionManager()
                    .startFractionScheduler()
                    .replace(ResourceTable.Id_fragment_container, mainFraction)
                    .submit();
            isHelp = false;
        } else {
            super.onBackPressed();
        }
    }

    /**
     * clearFocus等同于隐藏软键盘
     *
     * @param component
     */
    public static void clearFocus(Component component) {
        Component focusedComponent = findFocus(component, Component.FOCUS_NEXT);
        if (focusedComponent != null) {
            focusedComponent.clearFocus();
            return;
        }

        focusedComponent = findFocus(component, Component.FOCUS_PREVIOUS);
        if (focusedComponent != null) {
            focusedComponent.clearFocus();
        }
    }

    /**
     * findFocus
     *
     * @param component
     * @param direction
     * @return Component
     */
    public static Component findFocus(Component component, int direction) {
        if (component.hasFocus()) {
            return component;
        }
        Component focusableComponent = component;
        int i = INT_99;
        while (i-- > 0) {
            focusableComponent = focusableComponent.findNextFocusableComponent(direction);
            if (focusableComponent != null) {
                if (focusableComponent.hasFocus()) {
                    return focusableComponent;
                }
            } else {
                break;
            }
        }
        return null;
    }
}